package com.example.itcompanyinterview;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.util.Pair;
import android.view.View;
import android.view.Window;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

import com.example.itcompanyinterview.container.CustomArrayAdapter;
import com.example.itcompanyinterview.object.*;
import com.example.itcompanyinterview.tools.CommonJsonParser;
import com.example.itcompanyinterview.tools.CommonUrlRequest;
import com.example.itcompanyinterview.tools.CustomTitleSetter;
import com.example.itcompanyinterview.tools.LoadingDialogHelper;

public class ProblemListActivity extends Activity {

	private SubCategory _subCategory;
	private Handler _messageHandler;
	private int _already_load_problem_num = 0;
	private List<Problem> _problemList;
	private CustomArrayAdapter<Problem> _adapter;
	private LoadingDialogHelper _loadingHelper;
	private CustomTitleSetter _titleBar;

	private static String PROBLEM_CONTROLER = "Problem";
	private static String GET_PROBLEM_LIST_ACTION = "GetProblemList";
	private static int GET_PROBLEM_LIST = 0x03;
	private static int LOAD_PROBLEM_NUM_PER_ACTION = 10;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.activity_question_list);
		this.Initialize();
		this.setProblemListClickListener();
		this.initMessageHandler();
		this.getProblemListFromUrl();
	}
	
	private void Initialize() {
		Intent intent = this.getIntent();
		Bundle bundle = intent.getExtras();
		this._subCategory = (SubCategory)bundle.getSerializable("subcategory");
		
		_titleBar = new CustomTitleSetter(this);
        _titleBar.setTitle(this._subCategory.getName(), View.GONE, View.VISIBLE);
        
        this._loadingHelper = new LoadingDialogHelper(this);
        this._problemList = new ArrayList<Problem>();
        this.initListViewAdapterAndLoadMore();
	}
		
	private void initListViewAdapterAndLoadMore() {
		ListView problemListView = (ListView)this.findViewById(R.id.questionList);
		//problemListView.addFooterView(this.getLayoutInflater().inflate(R.layout.question_list_addmore, null));
		this._adapter = new CustomArrayAdapter<Problem>(this, this._problemList ,problemListView);
		problemListView.setAdapter(this._adapter);
		
		/*
		final Button addMoreButton = (Button)this.findViewById(R.id.load_more_question);
		addMoreButton.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View arg0) {
				addMoreButton.setVisibility(View.GONE);
				getProblemListFromUrl();
				addMoreButton.setVisibility(View.VISIBLE);
			}
			
		});
		*/
	}
	
	public void setProblemListClickListener() {
		ListView problemListView = (ListView) this
				.findViewById(R.id.questionList);
		problemListView.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View arg1, int pos,
					long id) {
				arg1.setSelected(true);
				Problem problem = (Problem) parent.getItemAtPosition(pos);
				Bundle bundle = new Bundle();
				bundle.putSerializable("problem", problem);
				Intent intent = new Intent(ProblemListActivity.this,
						ProblemDetailActivity.class);
				intent.putExtras(bundle);
				startActivity(intent);
			}
		});
	}
	
	private void initMessageHandler() {
    	this._messageHandler = new Handler() {

			@Override
			public void handleMessage(Message msg) {
				if(msg.what == GET_PROBLEM_LIST) {
					_loadingHelper.closeLoadingDialog();
					String problemJsonString = (String)msg.obj;
			    	if(problemJsonString == null) {
			    		Toast.makeText(ProblemListActivity.this, "获取列表失败，请检测网络",
			    				Toast.LENGTH_SHORT).show();
			    		return;
			    	}
			    	initProblemList(problemJsonString);
				}
				super.handleMessage(msg);
			}
    		
    	};
    }
	
	private void getProblemListFromUrl() {
		new Thread(new Runnable() {
			public void run() {
				List<Pair<String, String>> paramList = new ArrayList<Pair<String, String>>();
				CommonUrlRequest.setParam(paramList, "subcid", String.valueOf(_subCategory.getId()));
				CommonUrlRequest.setParam(paramList, "length", String.valueOf(LOAD_PROBLEM_NUM_PER_ACTION));
				CommonUrlRequest.setParam(paramList, "offset", String.valueOf(_already_load_problem_num));
				String roleProblemString = CommonUrlRequest
						.getControllerAndAction(ProblemListActivity.PROBLEM_CONTROLER,
								ProblemListActivity.GET_PROBLEM_LIST_ACTION, paramList);
				Message m = _messageHandler.obtainMessage();
				m.obj = roleProblemString;
				m.what = ProblemListActivity.GET_PROBLEM_LIST;
				_messageHandler.sendMessage(m);
			}
		}).start();
		this._loadingHelper.showLoadingDialog();
	}
	
	public void initProblemList(String jsonProblemString) {
		try {
			JSONObject jsonProblemRet = CommonJsonParser
					.parseJsonObject(jsonProblemString);
			if (jsonProblemRet.getInt("err") != 0) {
				Toast.makeText(ProblemListActivity.this,
						"获取失败:" + jsonProblemRet.getString("msg"),
						Toast.LENGTH_LONG).show();
				return;
			}

			JSONArray jsonProblemList = CommonJsonParser
					.parseJsonArray(jsonProblemRet.getString("value"));
			int problemNum = jsonProblemList.length();
			
			for (int i = 0; i < problemNum; i++) {
				JSONObject jsonProblemObj = jsonProblemList.getJSONObject(i);
				int id = jsonProblemObj.getInt("id");
				String title = jsonProblemObj.getString("title");
				
				_problemList.add(new Problem(id, this._subCategory.getId(), title));
			}
			
			this._adapter.notifyDataSetChanged();
			/*
			this._already_load_problem_num = this._already_load_problem_num + problemNum;
			if(ProblemListActivity.LOAD_PROBLEM_NUM_PER_ACTION > problemNum) {
				this.setMoreButtonUnClickable();
			}
			*/
		} catch (JSONException e) {
			Toast.makeText(ProblemListActivity.this,
					"发生了异常:" + e.getMessage(), Toast.LENGTH_LONG).show();
			Log.e("InitCompanyList", e.getMessage());
		}
	}
	
	/*
	private void setMoreButtonUnClickable() {
		Button loadMoreButton = (Button)this.findViewById(R.id.load_more_question);
		loadMoreButton.setText("已加载完成");
		loadMoreButton.setTextColor(Color.GRAY);
		loadMoreButton.setClickable(false);
	}
	*/
}
